package com.jiukuaidao.zhulin.module;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;

import com.jiukuaidao.library.Config;
import com.jiukuaidao.library.base.IBaseView;
import com.jiukuaidao.library.config.db.RealmEntity;
import com.jiukuaidao.library.net.MyRetroCallBack;
import com.jiukuaidao.library.net.MyRetroCallBytesBack;
import com.jiukuaidao.library.util.DBUtils;
import com.jiukuaidao.library.util.ToastUtil;
import com.jiukuaidao.zhulin.AppContext;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.api.ApiGetCode;
import com.jiukuaidao.zhulin.api.ApiGraphicCode;
import com.jiukuaidao.zhulin.api.ApiOrderFinishPay;
import com.jiukuaidao.zhulin.api.ApiOrderReceipt;
import com.jiukuaidao.zhulin.api.ApiShoppingCart;
import com.jiukuaidao.zhulin.api.ApiValidateGraphic;
import com.jiukuaidao.zhulin.data.TasksRepository;
import com.jiukuaidao.zhulin.entity.ApiShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.DBShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.EventShoppingCardFailed;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.shoppingcart.AddGoodsParamsInfo;
import com.jiukuaidao.zhulin.util.UserInfoUtil;
import com.ta.utdid2.android.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Author : PaiTaSuo
 * Date : 2016/5/26
 * Description :
 */
public class CommPresenter implements CommContract.Presenter {

    protected TasksRepository mRepository;
    protected CommContract.CommBaseView mView;

    private static int mGoodsCountTotal; //本地购物车商品总数量
    public static final String mFindKey = "mGoodsNumber";

    public CommPresenter(TasksRepository repository, CommContract.CommBaseView view) {
        mRepository = repository;
        mView = view;
    }

    /**
     * 发送短信
     */
    @Override
    public void getVeriCode() {
        if (StringUtils.isEmpty(((CommContract.CodeView) mView).getCodeMobile())) {
            ((CommContract.CodeView) mView).codeToast(AppContext.getContext().getString(R.string.phone_empty), "0");
            return;
        }
        if (((CommContract.CodeView) mView).getCodeMobile().length() != 11) {
            ((CommContract.CodeView) mView).codeToast(AppContext.getContext().getString(R.string.phone_error_hint), "0");
            return;
        }
        mRepository.loadData(new ApiGetCode(((CommContract.CodeView) mView).getCodeMobile(), new MyRetroCallBack() {
            @Override
            public void onSuccess(Object result, String errorCode, String msg) {
                MyCount mCountThread = new MyCount(60000, 1000, (CommContract.CodeView) mView);
                mCountThread.start();
                ((CommContract.CodeView) mView).codeToast(AppContext.getContext().getString(R.string.code_send_success_hint), "0");
            }

            @Override
            public void onFail(Object result, String errorCode, String msg) {
                ((CommContract.CodeView) mView).codeBtn().setClickable(true);
                ((CommContract.CodeView) mView).codeToast(msg, errorCode);

            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
                ((CommContract.CodeView) mView).codeBtn().setClickable(true);
                ((CommContract.CodeView) mView).codeToast(msg, String.valueOf(resCode));
            }
        }));
    }

    /**
     * 获取图形验证码
     */
    @Override
    public void getGraphicCode() {
        mRepository.loadData(new ApiGraphicCode(UserInfoUtil.get_app_key(AppContext.getContext()), new MyRetroCallBytesBack() {
            @Override
            public void onSuccess(InputStream inputStream) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                ((CommContract.GraphicCodeView) mView).getImgUrl(bitmap);
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {

            }
        }));
    }

    /**
     * 验证图形码
     */

    @Override
    public void validateGraphic() {
        mRepository.loadData((new ApiValidateGraphic(UserInfoUtil.get_app_key(AppContext.getContext()), ((CommContract.GraphicCodeView) mView).getGraphicCode(), new MyRetroCallBack() {
            @Override
            public void onSuccess(Object result, String errorCode, String msg) {
                ((CommContract.GraphicCodeView) mView).validateFinish();
            }

            @Override
            public void onFail(Object result, String errorCode, String msg) {
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
            }
        })));
    }


    public DBShoppingCartInfo mResult;

    @Override
    public void addShoppingCartLocal() {
        ExecutorService es = Executors.newSingleThreadExecutor();
        es.execute(new Runnable() {
                       @Override
                       public void run() {
                           final CommContract.ShoppingCartLocalView view = (CommContract.ShoppingCartLocalView) mView;
                           final RealmEntity realmEntity = DBUtils.findFirst(DBShoppingCartInfo.class, mFindKey
                                   , view.getGoodsNumber());

                           mResult = (DBShoppingCartInfo) realmEntity.getRealmModel();

                           if (mResult == null) {
                               DBUtils.getDefaultRealm().executeTransaction(new Realm.Transaction() {
                                   @Override
                                   public void execute(Realm realm) {
                                       mResult = realm.createObject(DBShoppingCartInfo.class);
                                       mResult.setGoodsNumber(view.getGoodsNumber());
                                       mResult.setCount(1);
                                       mResult.setPrice(view.getGoodsCurPrice());
                                       realm.close();
                                   }
                               });
                           } else {
                               final int count = mResult.getCount() + 1;
                               DBUtils.getDefaultRealm().executeTransaction(new Realm.Transaction() {
                                   @Override
                                   public void execute(Realm realm) {
                                       mResult.setCount(count);
                                       mResult.setPrice(view.getGoodsCurPrice());
                                       realm.close();
                                   }
                               });
                           }
                           getShoppingCartDataLocal();
                       }
                   }
        );
    }

    @Override
    public void reduceShoppingCartLocal() {
        ExecutorService es = Executors.newSingleThreadExecutor();
        es.execute(new Runnable() {
            @Override
            public void run() {

                CommContract.ShoppingCartLocalView view = (CommContract.ShoppingCartLocalView) mView;

                final RealmEntity realmEntity = DBUtils.findFirst(DBShoppingCartInfo.class, mFindKey
                        , view.getGoodsNumber());

                mResult = (DBShoppingCartInfo) realmEntity.getRealmModel();

                if (mResult == null) {
                    realmEntity.getRealm().close();
                    return;
                }

                if (mResult.getCount() == 0) {  //商品0个 不让减
                    realmEntity.getRealm().close();
                    return;
                }
                DBUtils.getDefaultRealm().executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        if (mResult.getCount() - 1 <= 0) {// 如果减1之后不足1，从数据库中删除
                            mResult.deleteFromRealm();
                        } else {
                            mResult.setCount(mResult.getCount() - 1);
                        }
                        realm.close();
                    }
                });
                getShoppingCartDataLocal();
            }
        });
    }


    @Override
    public synchronized void getShoppingCartDataLocal() {

        ExecutorService es = Executors.newSingleThreadExecutor();
        es.execute(new Runnable() {
            @Override
            public void run() {
                mGoodsCountTotal = 0;
                final RealmEntity realmEntity = DBUtils.findAll(DBShoppingCartInfo.class);
                final RealmResults<DBShoppingCartInfo> results = (RealmResults<DBShoppingCartInfo>) realmEntity.getRealmResults();

                if (results == null) {
                    EventBus.getDefault().post(new EventShoppingCardFailed());
                    return;
                }

                List<EventShoppingCartInfo> datas = new ArrayList<>(results.size());
                for (int i = 0; i < results.size(); i++) {
                    DBShoppingCartInfo result = results.get(i);

                    mGoodsCountTotal += result.getCount();

                    EventShoppingCartInfo info = new EventShoppingCartInfo();
                    info.setCount(result.getCount());
                    info.setPrice(result.getPrice());
                    info.setGoodsGN(result.getGoodsNumber());
                    datas.add(info);
                }

                realmEntity.getRealm().close();
                EventBus.getDefault().post(datas);
            }
        });

    }

    @Override
    public int getGoodsCountTotal() {
        return mGoodsCountTotal;
    }

    @Override
    public void getShoppingCartDataNet() {
        final CommContract.ShoppingCartNetView view = (CommContract.ShoppingCartNetView) mView;
        mRepository.loadData(new ApiShoppingCart(paramsToEntity(), new MyRetroCallBack<ApiShoppingCartInfo>() {
            @Override
            public void onSuccess(ApiShoppingCartInfo result, String errorCode, String msg) {
                if (result != null)
                    view.getShoppingCartDataNetSuc(result);
            }

            @Override
            public void onFail(ApiShoppingCartInfo result, String errorCode, String msg) {
                ((IBaseView)mView).hideLoading();
                switch (errorCode) {
                    case "401":  //401 没有商品了. count为0
                        EventBus.getDefault().post(new EventShoppingCardFailed());
                        break;
                }
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
                if (Config.Debug) {
                    ToastUtil.show("errorCode  :" + resCode + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
                }
               ((IBaseView)mView).hideLoading();
            }
        }));
    }


    @Override
    public AddGoodsParamsInfo paramsToEntity() {
        CommContract.ShoppingCartNetView view = (CommContract.ShoppingCartNetView) mView;
        AddGoodsParamsInfo params = new AddGoodsParamsInfo();
        params.shopId = view.getShopId();
        AddGoodsParamsInfo.PackList packList = new AddGoodsParamsInfo.PackList();
        packList.checked = "true";
        packList.count = 1;
        packList.name = "";
        packList.src = "";
        params.cart.packList.add(packList);
        if (view.getEventShoppingCartDatas() == null)
            return null;

        for (int i = 0; i < view.getEventShoppingCartDatas().size(); i++) {
            EventShoppingCartInfo result = view.getEventShoppingCartDatas().get(i);
            AddGoodsParamsInfo.CartItem cartItem = new AddGoodsParamsInfo.CartItem();
            cartItem.count = result.getCount();
            cartItem.gn = result.getGoodsGN();
            cartItem.checked = "true";
            cartItem.src = "";
            params.cart.packList.get(0).cartItems.add(cartItem);
        }
        return params;
    }

    @Override
    public void orderSign() {

        final CommContract.orderView view = (CommContract.orderView) mView;

        mRepository.loadData(new ApiOrderReceipt(view.getOrderNumber(), new MyRetroCallBack<String>() {
            @Override
            public void onSuccess(String result, String errorCode, String msg) {
                if (result != null) {
                    view.refreshInfo();
                    ToastUtil.show(R.string.order_receipted, Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onFail(String result, String errorCode, String msg) {
                ToastUtil.show(msg, Toast.LENGTH_SHORT);
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
                if (Config.Debug)
                    ToastUtil.show("errorCode  :" + resCode + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
            }
        }));

    }

    /**
     * 支付完调用接口
     */
    @Override
    public void getFinishPay() {
        mRepository.loadData(new ApiOrderFinishPay(((CommContract.FinishPayView) mView).getOrderNo(), ((CommContract.FinishPayView) mView).getStatus(), new MyRetroCallBack() {
            @Override
            public void onSuccess(Object result, String errorCode, String msg) {
                if (Config.Debug) {
                    ToastUtil.show(msg, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onFail(Object result, String errorCode, String msg) {
                if (Config.Debug) {
                    ToastUtil.show(msg, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError(Throwable t, int resCode, String msg) {
                if (Config.Debug) {
                    ToastUtil.show(msg, Toast.LENGTH_SHORT);
                }
            }
        }));
    }


//    @Override
//    public void addShoppingCartNet() {
//        mRepository.loadData(new ApiAddShoppingCart(((CommContract.ShoppingCartView) mView).getGoodsGN(), new MyRetroCallBack() {
//            @Override
//            public void onSuccess(Object result, String errorCode, String msg) {
//                if (result != null)
//                    loadShoppingCartData();
//            }
//
//            @Override
//            public void onFail(Object result, String errorCode, String msg) {
//                if (Config.Debug) {
//                    ToastUtil.show("errorCode  :" + result + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
//                }
//            }
//
//            @Override
//            public void onError(Throwable t, int resCode, String msg) {
//                if (Config.Debug) {
//                    ToastUtil.show("errorCode  :" + resCode + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
//                }
//            }
//        }));
//    }

//    @Override
//    public void reduceShoppingCartNet() {
//        mRepository.loadData(new ApiReduceShoppingCart(((CommContract.ShoppingCartView) mView).getGoodsGN(), new MyRetroCallBack<String>() {
//            @Override
//            public void onSuccess(String result, String errorCode, String msg) {
//                if (result != null)
//                    loadShoppingCartData();
//            }
//
//            @Override
//            public void onFail(String result, String errorCode, String msg) {
//                if (Config.Debug) {
//                    ToastUtil.show("errorCode  :" + errorCode + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
//                }
//            }
//
//            @Override
//            public void onError(Throwable t, int resCode, String msg) {
//                if (Config.Debug) {
//                    ToastUtil.show("errorCode  :" + resCode + "\n errorMsg :" + msg, Toast.LENGTH_SHORT);
//                }
//            }
//        }));
//    }

}
